package light.head.controller.mobile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.sys.OrganDAO;
import light.head.dao.sys.UserInfoDAO;
import light.head.framework.base.SupporterController;
import light.head.framework.utils.MD5Utils;
import light.head.model.Organ;
import light.head.model.UserInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 手机版登陆
 * @author yangguanghe @date 2014-5-5 @time 下午3:42:12
 */
@Controller
public class MobileLoginController extends SupporterController {
	private UserInfoDAO userDAO;
	private OrganDAO organDAO;
	
	@RequestMapping(Url.C_MOBILE_LOGIN)
	public void login2(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String email = request.getParameter(Parm.EMAIL);
		String pwd = request.getParameter(Parm.PWD);
		
		if (!isNotNull(email) || !isNotNull(pwd)) {
			response.getWriter().print(Msg.PARAMETER_ERROR);
			return;
		}
		UserInfo user = userDAO.getByEmail(email);
		if (null == user)
			print(response, Msg.NOT_FIND);
		else if (!user.getPwd().equals(MD5Utils.encryptTo32(pwd)))
			print(response, Msg.PWD_ERROR);
		else {
			if (true == user.getDeleted() && !Sys.ADMIN.equals(user.getRealName())) {
				print(response, Msg.DELETED);
			} else {
				HttpSession session = request.getSession();
				session.setAttribute(Parm.CU_CODE, user.getCode());
				session.setAttribute(Parm.CU_EMAIL, user.getEmail());
				session.setAttribute(Parm.CU_REAL_NAME, user.getRealName());
				
				// 在拦截器中使用该角色code判断是否有操作权限
				session.setAttribute(Parm.CU_ROLE_CODE, user.getRc());
				session.setAttribute(Parm.CU_IS_MANAGER, user.getIsManager());
				session.setAttribute(Parm.CU_ORGAN_TYPE_CODE, user.getOtc());

				// 在所有业务操作中，都需要该属性来判断用户能查询的数据
				session.setAttribute(Parm.CU_ORGAN_CODE, user.getOc());
				session.setAttribute(Parm.CU_ORGAN_NAME, user.getOn());
				
				Organ root = organDAO.getRoot(user.getOc());
				session.setAttribute(Parm.CU_ROOT_ORGAN_CODE, null != root ? root.getCode() : null);
				
				// 页面样式需要使用
				session.setAttribute(Parm.CU_PAGE_STYLE, user.getPageStyle());

				print(response, Msg.SUCCESS);
			}
		}
	}

	
	@Autowired
	public void setUserDAO(UserInfoDAO userDAO) {
		this.userDAO = userDAO;
	}
	
	@Autowired
	public void setOrganDAO(OrganDAO organDAO) {
		this.organDAO = organDAO;
	}

	
}
